<template>
  <div id="userLoginPage">
    <h1 class="title">胡图图库 | 用户注册</h1>
    <div class="desc">——智能协同云图库平台</div>
    <a-form :model="formState" name="basic" autocomplete="off" @finish="handleSumit">
      <a-form-item name="userAccount" :rules="[{ required: true, message: '请输入账号！' }]">
        <a-input v-model:value="formState.userAccount" placeholder="请输入账号" />
      </a-form-item>

      <a-form-item
        name="userPassword"
        :rules="[
          { required: true, message: '请输入密码!' },
          { min: 8, message: '密码不能小于8位' },
        ]"
      >
        <a-input-password v-model:value="formState.userPassword" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item
        name="checkPassword"
        :rules="[
          { required: true, message: '请确认密码是否正确!' },
          { min: 8, message: '密码不能小于8位' },
        ]"
      >
        <a-input-password v-model:value="formState.checkPassword" placeholder="请再次输入密码" />
      </a-form-item>
      <a-form-item
        name="userEmail"
        :rules="[
          { required: true, message: '请输入邮箱' },
          { type: 'email', message: '请输入有效邮箱' },
        ]"
      >
        <a-input v-model:value="formState.userEmail" placeholder="请输入邮箱" />
      </a-form-item>
      <!-- 验证码 -->
      <a-input-group compact>
        <a-input
          v-model:value="formState.emailCode"
          placeholder="请输入6位验证码"
          style="width: calc(100% - 130px)"
        />
        <a-button
          type="primary"
          :disabled="countdown > 0"
          :loading="sending"
          @click="sendEmailMessage"
          >{{ captchaButtonText }}
        </a-button>
      </a-input-group>
      <div class="tips">
        已有账号？
        <router-link to="/user/login">去登录</router-link>
      </div>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 100%">注册</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { computed, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'
import { sendEmailCodeUsingPost, userRegisterUsingPost } from '@/api/userController'

const router = useRouter()
const loginUserStore = useLoginUserStore()

const isEmailValid = ref(false)
const emailRegex = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/

const formState = reactive<API.UserRegisterRequest>({
  userAccount: '',
  userEmail: '',
  emailCode: '',
  userPassword: '',
  checkPassword: '',
})

/**
 * 提交表单
 * @param values
 */
const handleSumit = async (values: any) => {
  // 判断两次输入密码是否一致
  if (formState.userPassword !== formState.checkPassword) {
    message.error('两次输入的密码不一致')
    return
  }
  if(formState.emailCode === ''){
    message.error('请输入验证码')
    return
  }
  const res = await userRegisterUsingPost({
      ...values,
      emailCode: formState.emailCode
  }
  )
  // 注册成功，跳转到登录页
  if (res.data.code === 0 && res.data.data) {
    message.success('注册成功，跳转到登录页~')
    router.push({
      path: '/user/login',
      replace: true,
    })
  } else {
    message.error('注册失败，' + res.data.message)
  }
}

/**
 * 发送邮箱验证码
 */
// 控制发送按钮状态
const sending = ref(false)
const sendEmailMessage = async (email: any) => {
  /** 验证邮箱 */
  if (formState.userEmail === '') {
    message.error('请先输入邮箱')
    return
  }
  // 1、正则验证
  isEmailValid.value = emailRegex.test(formState.userEmail)
  if (isEmailValid.value === false) {
    message.error('请输入有效的邮箱')
    return
  }
  try {
    sending.value = true
    const res = await sendEmailCodeUsingPost({ targetEmail: formState.userEmail })
    if (res.data.code === 0 && res.data.data) {
      message.success('验证码发送成功，请注意查收~')
      sending.value = false
      startCountdown()
    } else {
      message.error('发送失败，' + res.data.message)
    }
  } catch (e) {
    message.error('请求失败，请检查网络')
  } finally {
    sending.value = false
  }
}

/**
 * 60秒倒计时交互
 */
const countdown = ref(0)


const captchaButtonText = computed(() =>
  countdown.value > 0 ? `${countdown.value}秒后重试` : '获取验证码',
)

// 启动倒计时
const startCountdown = (seconds = 60) => {
  countdown.value = seconds
  const timer = setInterval(() => {
    if (countdown.value <= 0) {
      clearInterval(timer)
      return
    }
    countdown.value -= 1
  }, 1000)
}

</script>
<style scoped>
#userLoginPage {
  max-width: 360px;
  margin: 0 auto;
}

.title {
  text-align: center;
  margin-bottom: 16px;
}

.desc {
  text-align: right;
  margin-bottom: 13px;
}

.tips {
  margin-bottom: 16px;
  font-size: 13px;
  color: #888;
  text-align: right;
}
</style>
